/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package crm.salesOrderProcessing.session;

import commonInfrastructure.accountManagement.entity.SalesmanEntity;
import crm.clientManagement.entity.CompanyEntity;
import crm.clientManagement.session.CompanySessionBean;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import crm.salesOrderProcessing.entity.LineItemEntity;
import crm.salesOrderProcessing.entity.ProductEntity;
import crm.salesOrderProcessing.entity.SalesInquiryEntity;
import crm.salesOrderProcessing.util.exception.SalesException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.EJB;

/**
 *
 * @author frankxgz
 */
@Stateless
@LocalBean
public class SalesInquirySessionBean {

    @PersistenceContext
    private EntityManager em;
    @EJB
    private PriceManagementSessionBean priceManage = new PriceManagementSessionBean();
    
    private CompanyEntity company;
    
    @EJB
    CompanySessionBean companySession = new CompanySessionBean();
    
    public SalesInquiryEntity addSalesInquiry(Long companyId, List productIds, List quantities)throws SalesException,ParseException{
        SalesInquiryEntity inquiry = new SalesInquiryEntity();
        company = em.find(CompanyEntity.class, companyId);        
        inquiry.setCompany(company);
        inquiry.setRaiseDate(getTodayDate());
        em.persist(inquiry);
        
        List<LineItemEntity> lineItems = createLineItems(createProductList(productIds),quantities);
        inquiry.setInquiryLineItems(lineItems);
        
        return inquiry;
    }
    
    public SalesInquiryEntity saveSalesInquiry(Long inquiryId,List productIds, List quantities)throws SalesException{
        SalesInquiryEntity inquiry = em.find(SalesInquiryEntity.class,inquiryId);
        company = inquiry.getCompany();
        List<LineItemEntity> lineItems = createLineItems(createProductList(productIds),quantities);
        inquiry.setInquiryLineItems(lineItems);
        em.merge(inquiry);
        return inquiry;
    }
    
    public void deleteInquiryLineItems(Long inquiryId){
        SalesInquiryEntity inquiry = em.find(SalesInquiryEntity.class, inquiryId);
        List <LineItemEntity> lineItems = inquiry.getInquiryLineItems();
        for (Object o: lineItems){
            LineItemEntity li = (LineItemEntity)o;
            em.remove(li);
        }
        inquiry.setInquiryLineItems(null);
        em.flush();
    }
    
    public void deleteSalesInquiry(Long inquiryId){
        SalesInquiryEntity inquiry = em.find(SalesInquiryEntity.class,inquiryId);
        List <LineItemEntity> lineItems = inquiry.getInquiryLineItems();
        for (Object o: lineItems){
            LineItemEntity li = (LineItemEntity)o;
            em.remove(li);
        }
        em.remove(inquiry);
    }
    
    public List<SalesInquiryEntity> getAllSalesInquiry(){
        Query query = em.createQuery("SELECT s1 FROM SalesInquiryEntity s1");
        return query.getResultList();
    }
    
    public List<SalesInquiryEntity> getInquiryByUser(SalesmanEntity user){
        List<CompanyEntity> companyList = companySession.getCompaniesBySalesman(user.getId());
        List<SalesInquiryEntity> inquiryList = new ArrayList<SalesInquiryEntity>();
        for (int i=0;i<companyList.size();i++){
            for (int j=0;j<companyList.get(i).getSalesInquiries().size();j++){
                inquiryList.add(companyList.get(i).getSalesInquiries().get(j));
            }
        }
        return inquiryList;
    }
    
    public CompanyEntity getCompany(Long id){
        CompanyEntity company = em.find(CompanyEntity.class, id);
        return company;
    }
    
    public CompanyEntity getCompanyByName(String companyName){
         
        Query query = em.createQuery("SELECT c FROM CompanyEntity c WHERE c.name = :inCompanyName");
        query.setParameter("inCompanyName", companyName);
        CompanyEntity company = null;
        try{
            company = (CompanyEntity)query.getSingleResult();
        }
        catch(NoResultException ex){
            ex.printStackTrace();
        }
        return company;
     }
    
    public ProductEntity getProduct(Long id){
        ProductEntity product = em.find(ProductEntity.class, id);
        return product;
    }
    
    public List createProductList(List productIds){
        List<ProductEntity> products = new ArrayList<ProductEntity>();
        ProductEntity product;
        for (Object o: productIds){
            Long productId = (Long)o;
            product = getProduct(productId);
            products.add(product);
        }
        return products;
    }
    
    public List<LineItemEntity> createLineItems(List products, List quantities)throws SalesException{
        List<LineItemEntity> lineItems = new ArrayList<LineItemEntity>();
        
        int length = products.size();
        for (int i=0; i<length; i++){
            LineItemEntity lineItem = new LineItemEntity();
            lineItem.setProduct((ProductEntity)products.get(i));
            lineItem.setQuantity(((Integer)quantities.get(i)).intValue());
            double[] price = priceManage.calculatePirce(company.getCompanyType(),(ProductEntity)products.get(i),((Integer)quantities.get(i)).intValue());
            lineItem.setPrice(price[1]);
            lineItem.setDiscount(price[0]);
            lineItem.setCumAmount(roundTwoDecimals(price[1]*((Integer)quantities.get(i)).intValue()));
            em.persist(lineItem);
            lineItems.add(lineItem);
        }
        return lineItems;
    }
    
    public SalesInquiryEntity getInquiryById(Long id){
        try{
            SalesInquiryEntity iq = em.find(SalesInquiryEntity.class,id);
            return iq;
        }catch (NoResultException ex) {
            return null;
        }
    }
    
    public double roundTwoDecimals(double d) {
        DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
    }
    

    
    private Date getTodayDate()throws ParseException{
       Calendar calendar = Calendar.getInstance();
       SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 
       String dateString= dateFormat.format(calendar.getTime());
       return dateFormat.parse(dateString);   
      
    }
}
